﻿using OfficeMiddlewareCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using WebSocketSharp.Server;

namespace OfficeMiddleware
{
    public partial class MainForm : Form
    {

        public MainForm()
        {
     
            InitializeComponent();

            WebSocketResponse.Server = new WebSocketServer(10270);
            WebSocketResponse.Server.AddWebSocketService<MainHub>("/");
            this.btnStart_Click(null, null);

            //this.Height = 600;
            //this.Width = 800;
            //this.ShowInTaskbar = true;
            //this.Left = 1;
            //this.Top = 1;
            //this.Opacity = 1;
            //this.FormBorderStyle = FormBorderStyle.Sizable;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            this.btnStart.Enabled = false;
            this.txtPort.ReadOnly = true;
            this.btnStop.Enabled = true;

            // _disposable = WebApp.Start($"{_uri}:{this.txtPort.Text}");
            var beginTime = DateTime.Now.AddMinutes(5);
            var index = 1;
            while (true)
            {
                try
                {
                    WebSocketResponse.Server.Start();
                    break;
                }
                catch (System.InvalidOperationException ex)
                {
                    LogHelper.Error($"启动Webscoket失败({index++})", ex);
                    if (ex.InnerException is System.Net.Sockets.SocketException se)
                    {
                        if (se.ErrorCode == 10048)
                        {
                            MessageBox.Show("正文运行环境端口(10270)被占用，启动失败");
                            Environment.Exit(0);

                        }
                    }
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    Thread.Sleep(1000);
                }
                if (DateTime.Now > beginTime)
                {
                    MessageBox.Show("正文运行环境，启动（重试）5分钟失败。");
                    Environment.Exit(0);


                }
            }

            var a = new List<string>();
            var c = a.Any();
            var d = a.Count();
            c = a.Count == 0;


        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            this.btnStop.Enabled = false;
            this.txtPort.ReadOnly = false;
            this.btnStart.Enabled = true;

            WebSocketResponse.Server.Stop();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {

        }


        protected override CreateParams CreateParams
        {
            get
            {
                var cp = base.CreateParams;
                cp.ExStyle |= 0x80;
                return cp;
            }
        }

    }


}
